<template>
  <div class="category-container">
    <!-- 顶部操作栏 -->
    <div class="top-bar">
      <!-- 搜索区域 -->
      <div class="search-area">
        <el-input v-model="searchForm.name" placeholder="输入类别名称查询" style="width: 200px; margin-right: 10px;"
          clearable />
        <el-select v-model="searchForm.status" placeholder="显示启用类别" style="width: 150px; margin-right: 10px;">
          <el-option label="全部" :value="-1" />
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
        <el-button type="primary" @click="searchGoodsType">
          查询
        </el-button>
      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button class="!ml-0" type="primary" @click="openAddDialog">
          新增
        </el-button>
        <el-button @click="batchClose">禁用</el-button>
        <el-button @click="batchOpen">启用</el-button>
        <el-button @click="refresh">刷新</el-button>
      </div>

      <!-- 新增 / 编辑对话框 -->
      <el-dialog v-model="dialogFormVisible" :title="dialogGoodsType === 'add' ? '新增商品类别' : '编辑商品类别'" width="500">
        <el-form :model="form">
          <el-form-item label="上级分类" :label-width="formLabelWidth">
            <el-tree-select v-model="form.parentId" :data="treeSelectData" filterable style="width: 240px"
              :props="{ value: 'id', label: 'name', children: 'children' }" :check-strictly="true" clearable>
              <template #default="{ data }">
                <span>
                  <el-icon>
                    <Folder v-if="data.children && data.children.length > 0" />
                    <Document v-else />
                  </el-icon>
                  {{ data.name }}
                </span>
              </template>
            </el-tree-select>
          </el-form-item>

          <el-form-item label="类别名称" :label-width="formLabelWidth">
            <el-input v-model="form.name" autocomplete="off" style="width: 240px" />
          </el-form-item>
        </el-form>

        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="saveGoodsType" :loading="saving">
              确认
            </el-button>
            <el-button @click="dialogFormVisible = false">取消</el-button>
          </div>
        </template>
      </el-dialog>
    </div>

    <!-- 数据表格 -->
    <el-table :data="tableData" border style="width: 100%" row-key="id"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" :default-expand-all="!searchMode"
      v-loading="tableLoad" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />

      <el-table-column prop="name" label="类别" width="300">
        <template #default="{ row }">
          {{ row.name }}
        </template>
      </el-table-column>

      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-switch :model-value="row.status" :active-value="1" :inactive-value="0"
            @change="() => handleStatusChange(row)" />
        </template>
      </el-table-column>

      <el-table-column prop="operation" label="操作" width="120">
        <template #default="{ row }">
          <el-button size="small" @click="openEditDialog(row.id)">
            <el-icon>
              <Edit />
            </el-icon>
          </el-button>
          <el-button size="small" @click="deleteGoodsType(row)" :loading="deleteLoadingId === row.id">
            <el-icon>
              <Delete />
            </el-icon>
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { Folder, Document, Edit, Delete } from '@element-plus/icons-vue'

const formLabelWidth = '80px'

// 是否在搜索（控制树形/平铺）
const searchMode = ref(false)

// 表格加载状态
const tableLoad = ref(false)

// 保存按钮状态
const saving = ref(false)

// 删除按钮状态（记录正在删除的行）
const deleteLoadingId = ref(null)

// 搜索表单
const searchForm = ref({
  name: '',
  status: 1 // 1 = 启用, 0 = 禁用, -1 = 全部
})

// 添加、修改表单
const form = ref({
  parentId: '0',
  name: ''
})

// 对话框、对话框类型
const dialogFormVisible = ref(false)
const dialogGoodsType = ref('add')

// 商品类别列表（扁平）
const goodsTypeList = ref([])

// 显示在表格中的数据（树形 or 扁平）
const tableData = computed(() =>
  searchMode.value ? goodsTypeList.value : treeData.value
)

// 树形数据
const treeData = computed(() => {
  const roots = []
  const map = {}

  goodsTypeList.value.forEach(item => {
    map[item.id] = { ...item, children: [] }
  })

  goodsTypeList.value.forEach(item => {
    const parentId = item.parentId
    if (parentId === null || parentId === '0' || parentId === 0) {
      roots.push(map[item.id])
    } else {
      const parentObj = map[parentId]
      if (parentObj) {
        parentObj.children.push(map[item.id])
      }
    }
  })

  return roots
})

// TreeSelect 数据，加一层“全部”
const treeSelectData = computed(() => [
  {
    id: '0',
    name: '全部',
    children: treeData.value
  }
])

// 打开新增弹窗
const openAddDialog = () => {
  dialogGoodsType.value = 'add'
  form.value = {
    parentId: '0',
    name: ''
  }
  dialogFormVisible.value = true
}

// 打开编辑弹窗
const openEditDialog = async (id) => {
  dialogGoodsType.value = 'edit'
  try {
    const { data } = await axios.get('/api/basic/goods/goodsTypeById', {
      params: { id }
    })
    if (data.code === 5200) {
      form.value = data.goodsType
      dialogFormVisible.value = true
    } else {
      ElMessage.error(data.msg || '获取数据失败')
    }
  } catch (error) {
    ElMessage.error(error.message || '获取数据失败')
  }
}

// 获取商品类别
const getGoodsType = async () => {
  tableLoad.value = true

  const params = {
    name: searchForm.value.name?.trim() || null,
    status:
      searchForm.value.status === -1 ? null : searchForm.value.status
  }

  try {
    const { data } = await axios.get('/api/basic/goods/allGoodsType', {
      params
    })

    if (data.code === 5200) {
      goodsTypeList.value = data.goodsTypeList || []
    } else {
      ElMessage.error(data.msg || '获取列表失败')
    }
  } catch (error) {
    ElMessage.error(error.message || '获取列表失败')
  } finally {
    tableLoad.value = false
  }
}

// 查询
const searchGoodsType = () => {
  const hasKeyword = !!searchForm.value.name?.trim()
  const status = searchForm.value.status

  // 有关键字、或筛选禁用/全部时使用平铺模式，其他用树形
  if (hasKeyword || status === 0 || status === -1) {
    searchMode.value = true
  } else {
    searchMode.value = false
  }

  getGoodsType()
}

// 刷新
const refresh = () => {
  searchForm.value = { name: '', status: 1 }
  searchMode.value = false
  getGoodsType()
}

// 保存
const saveGoodsType = async () => {
  if (!form.value.name || !form.value.name.trim()) {
    ElMessage.warning('请输入类别名称')
    return
  }

  saving.value = true

  try {
    const url =
      dialogGoodsType.value === 'add'
        ? '/api/basic/goods/addGoodsType'
        : '/api/basic/goods/updateGoodsType'

    const { data } = await axios.post(url, {
      ...form.value,
      name: form.value.name.trim()
    })

    if (data.code === 5200) {
      ElMessage.success(data.msg || '保存成功')
      dialogFormVisible.value = false
      await getGoodsType()
    } else {
      ElMessage.error(data.msg || '保存失败')
    }
  } catch (error) {
    ElMessage.error(error.message || '保存失败')
  } finally {
    saving.value = false
  }
}

// 删除
const deleteGoodsType = async (row) => {
  if (row.children && row.children.length > 0) {
    ElMessage.error('当前类别下有子类别，请先删除子类别')
    return
  }

  try {
    await ElMessageBox.confirm(
      '此操作将永久删除该类别, 是否继续?',
      '删除类别',
      { type: 'warning' }
    )
  } catch {
    ElMessage.info('取消删除')
    return
  }

  deleteLoadingId.value = row.id
  try {
    const { data } = await axios.post(
      '/api/basic/goods/deleteGoodsType',
      null,
      { params: { id: row.id } }
    )
    if (data.code === 5200) {
      ElMessage.success(data.msg || '删除成功')
      await getGoodsType()
    } else {
      ElMessage.error(data.msg || '删除失败')
    }
  } catch (error) {
    ElMessage.error(error.message || '删除失败')
  } finally {
    deleteLoadingId.value = null
  }
}

// 状态变更
const handleStatusChange = async (row) => {
  tableLoad.value = true
  const originalStatus = row.status
  const targetStatus = originalStatus === 1 ? 0 : 1

  try {
    const { data } = await axios.post(
      '/api/basic/goods/updateGoodsTypeStatus',
      null,
      {
        params: {
          id: row.id,
          status: targetStatus
        }
      }
    )

    if (data.code !== 5200) {
      ElMessage.error(data.msg || '状态更新失败')
    } else {
      ElMessage.success('状态更新成功')
      await getGoodsType()
    }
  } catch (error) {
    ElMessage.error(error.message || '网络错误，请重试')
  } finally {
    tableLoad.value = false
  }
}

// 选中的对象
const selections = ref([])

// 选中的id
const selectionIds = computed(() => selections.value.map(item => item.id))

// 选中多选框
const handleSelectionChange = (selection) => {
  selections.value = selection
}

// 批量禁用
const batchClose = async () => {
  if (selectionIds.value.length === 0) {
    ElMessage.warning('请先选择')
    return
  }
  await batchUpdateStatus(0)
}

// 批量启用
const batchOpen = async () => {
  if (selectionIds.value.length === 0) {
    ElMessage.warning('请先选择')
    return
  }
  await batchUpdateStatus(1)
}

// 批量修改状态
const batchUpdateStatus = async (status) => {
  const params = {
    ids: selectionIds.value,
    status
  }

  try {
    const { data } = await axios.post(
      '/api/basic/goods/batchUpdateGoodsTypeStatus',
      params
    )
    if (data.code === 5200) {
      ElMessage.success(data.msg || '修改成功')
      await getGoodsType()
    } else {
      ElMessage.error(data.msg || '修改失败')
    }
  } catch (error) {
    ElMessage.error(error.message || '修改失败')
  }
}

onMounted(() => {
  getGoodsType()
})
</script>

<style scoped>
.category-container {
  padding: 20px;
  background-color: #fff;
}

.top-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-area {
  display: flex;
  align-items: center;
  gap: 10px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.el-table {
  margin-top: 10px;
}

/* 表格行样式 */
.el-table .el-table__row:nth-child(even) {
  background-color: #f5f7fa;
}

/* 缩进样式 */
.el-table .el-table__row>td:nth-child(2) {
  padding-left: 20px;
}

/* 操作按钮样式 */
.el-button--small {
  padding: 5px 8px;
  font-size: 12px;
}

/* 开关样式 */
.el-switch {
  margin-left: 10px;
}
</style>
